package com.dc.core.xxljob.controller;

import cn.dev33.satoken.annotation.SaCheckLogin;
import cn.hutool.core.io.IoUtil;
import cn.hutool.http.HttpUtil;
import cn.hutool.http.Method;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.ssssssss.magicapi.core.annotation.Valid;

import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.nio.charset.Charset;
import java.nio.charset.StandardCharsets;
import java.util.Enumeration;
import java.util.HashMap;
import java.util.Map;

@Controller
@Slf4j
public class XxlJobProxyController {

    @Value("${server.servlet.context-path}")
    private String contextPath;

    @RequestMapping("/xxl-job-admin/**")
    @ResponseBody
    @SaCheckLogin
    public Object proxy(HttpServletRequest request) throws IOException {

        String requestURI = request.getRequestURI();
        String path = requestURI.replaceAll(contextPath, "");
        log.error("url:"+"http://rgblive.cn"+path);
        log.error("method:"+request.getMethod());
        Map<String,Object> params = new HashMap<>();
        Map<String, String[]> parameterMap = request.getParameterMap();
        for (Map.Entry<String, String[]> stringEntry : parameterMap.entrySet()) {
            String s = stringEntry.getKey();
            params.put(s,request.getParameter(s));
        }
        log.error("param:",params);
        String bodyData = HttpUtil.toParams(params, StandardCharsets.UTF_8);

        String body = HttpUtil.createRequest(Method.valueOf(request.getMethod()),
                        "http://localhost:8080"+path)
                .header("content-type",request.getHeader("content-type"))
                .body(bodyData)
                .execute().body();
        return body;
    }

}
